<?php

/**
 * Zeed Platform Project
 * Based on Zeed Framework & Zend Framework.
 *
 * LICENSE
 * http://www.zeed.com.cn/license/
 *
 * @category Zeed
 * @package Zeed_ChangeMe
 * @subpackage ChangeMe
 * @copyright Copyright (c) 2010 Zeed Technologies PRC Inc. (http://www.zeed.com.cn)
 * @author Zeed Team (http://blog.zeed.com.cn)
 * @since 2010-12-6
 * @version SVN: $Id$
 */
class ContentController extends ArchiveAdminAbstract
{
    protected $perpage = 20;

//     protected $_permission_share = 200005; // 权限 - 详情
//     protected $_permission_share = 200005; // 权限 - 编辑
//     protected $_permission_share = 200005; // 权限 - 授权

    /**
     * 案件列表
     */
    public function index()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $ordername = $this->input->get('ordername', null);
        $orderby = $this->input->get('orderby', null);
        $page = (int)$this->input->get('pageIndex', 0);
        $perpage = (int)$this->input->get('pageSize', $this->perpage);
        $key = trim($this->input->get('key'));
        $time_start = $this->input->get('time_start');
        $time_end = $this->input->get('time_end');
        $category_name = $this->input->get('category_name');
        $department_name = $this->input->get('department_name');
        $dot = $this->input->get('dot');
        
        /* ajax 加载数据 */
        if ($this->input->isAJAX()) {
            $offset = $page * $perpage;
            $page = $page + 1;

            /* 组织查询条件 */
            $where = array('status' => array('$in' => array(-2, 1)));
            
            /* 处理打点条件 */
            if ($dot) {
                $where_dot = array('status' => 1, 'mediatype' => $dot);
            }

            if ($time_start && $time_end) {
                /* 处理时间排序 */
                $time_se = array($time_start, $time_end);
                asort($time_se);
                $time_se = array_values($time_se);
                $time_start = $time_se[0];
                $time_end = $time_se[1];

                $where['$and'][] = array(
                    '$and' => array(
                        array('ctime' => ['$gte' => strtotime($time_start) * 1000]),
                        array('ctime' => ['$lte' => (strtotime($time_end) + 24 * 3600 - 1) * 1000]),
                    )
                );
                $where_dot['$and'][] = array(
                    '$and' => array(
                        array('ctime_archive' => ['$gte' => strtotime($time_start) * 1000]),
                        array('ctime_archive' => ['$lte' => (strtotime($time_end) + 24 * 3600 - 1) * 1000]),
                    )
                );
            } else {
                if ($time_start) {
                    $startime = strtotime($time_start) * 1000; // new MongoDate(strtotime($time_start));
                    $where['ctime'] = $where_dot['ctime_archive'] = ['$gte' => $startime];
                }

                if ($time_end) {
                    $endtime = (strtotime($time_end) + 24 * 3600 - 1) * 1000;
                    $where['ctime'] = $where_dot['ctime_archive'] = ['$lte' => $endtime];
                }
            }
            if ($category_name) {
                $where['$and'][] = $where_dot['$and'][] = array('category_name' => new MongoRegex("/$category_name/i"));
            }
            if ($department_name) {
                $where['$and'][] = $where_dot['$and'][] = array('department_name' => new MongoRegex("/$department_name/i"));
            }
            if ($key) {
                $where['$and'][] = array(
                    '$or' => array(
                        array('sn' => new MongoRegex("/$key/i")),
                        array('title' => new MongoRegex("/$key/i")),
                        array('description' => new MongoRegex("/$key/i")),
                        array('address' => new MongoRegex("/$key/i")),
                        array('label' => new MongoRegex("/$key/i")),
                    )
                );
                $where_dot['$and'][] = array(
                    '$or' => array(
                        array('content' => new MongoRegex("/$key/i")),
                    )
                );
            }
            $order = array('ctime' => 'DESC');
            $order_dot = array('ctime_archive' => -1);
            
            /* 执行查询 */
            if ($dot) {
                $content = Attachment_Model_Content_Dot::instance()->getArchiveFromDot($where_dot, $order_dot, $perpage, $offset);
                $data['count'] = Attachment_Model_Content_Dot::instance()->getArchiveFromDotCount($where_dot);
            } else {
                $content = Archive_Model_Content::instance()->fetchByWhere($where, $order, $perpage, $offset);
                $data['count'] = Archive_Model_Content::instance()->getCount($where);
            }
            
            /* 处理其他一些信息 */
            if (! empty($content)) {
                foreach ($content as $k => &$v) {
                    /* 处理案件名称 */
                    $v['title_sub'] = $v['title'];
                    if (mb_strlen($v['title_sub']) > 16) {
                        $v['title_sub'] = mb_substr($v['title_sub'], 0, 16);
                    }

                    /* 处理时间 */
                    if (strlen($v['ctime']) == 13) {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime'] / 1000);
                    } else {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime']);
                    }
                    if (strlen($v['mtime']) == 13) {
                        $v['mtime'] = date(DATETIME_FORMAT, $v['mtime'] / 1000);
                    } else {
                        $v['mtime'] = date(DATETIME_FORMAT, $v['mtime']);
                    }

                    /* 处理行动次数 */
                    $where_card = array('sn' => $v['sn'], 'status' => 1);
                    $v['count_card'] = Archive_Model_Card::instance()->getCount($where_card);
                }
            }

            $data['content'] = $content ? $content : array();
        }
        
        /* 获取案件类型 */
        $categories = Archive_Model_Category::instance()->getAllCategoriesForSelect();
        
        /* 获取承办部门 */
        $where_department = array('status' => 1);
        $order_department = "sort_order ASC";
        $departments = Archive_Model_Department::instance()->fetchByWhere($where_department, $order_department);

        /* 获取删除二次确认人信息 */
        $where_users_confirm = "u.status = 1 AND u.userid != 1 AND g.groupid = 1";
        $cols_users_confirm = array('u.userid', 'u.username', 'u.fullname');
        $users_confirm = Admin_Model_User::instance()->getUsersByGroupid($where_users_confirm, null, null, null, $cols_users_confirm);
        if (! empty($users_confirm)) {
            foreach ($users_confirm as $kk => $vv) {
                if ($vv['userid'] == $this->_userid) {
                    unset($users_confirm[$kk]);
                }
            }
        }

        $data['categories'] = $categories;
        $data['departments'] = $departments;
        $data['users_confirm'] = $users_confirm;

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.index');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 添加
     */
    public function add()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        if ($this->input->isPOST()) {
            $this->addSave();
            return self::RS_SUCCESS;
        }

        /* 获取案件类型 */
        $where_category = array('status' => 1);
        $order_category = "sort_order ASC";
        $categories = Archive_Model_Category::instance()->fetchByWhere($where_category, $order_category);
        $category_names = array();
        if (! empty($categories)) {
            foreach ($categories as $k => $v) {
                $category_names[] = $v['title'];
            }
        }

        /* 获取承办部门 */
        $where_department = array('status' => 1);
        $order_department = "sort_order ASC";
        $departments = Archive_Model_Department::instance()->fetchByWhere($where_department, $order_department);
        $department_names = array();
        if (! empty($departments)) {
            foreach ($departments as $k => $v) {
                $department_names[] = $v['department_name'];
            }
        }

        /* 获取热门标签 - 限制20条 */
        $order_label = array('rel_count' => 'DESC');
        $limit_label = 20;
        $labels = Trend_Model_Label::instance()->fetchByWhere(array(), $order_label, $limit_label);
        $labels_title = array();
        if (! empty($labels)) {
            foreach ($labels as $k => $v) {
                $labels_title[] = $v['title'];
            }
        }

        /* 设置一些默认值 */
        $content = array(
            'tte' => date('Y-m-d')
        );

        $data = array(
            'categories' => $categories,
            'departments' => $departments,
            'category_names' => ! empty($category_names) ? json_encode($category_names, JSON_UNESCAPED_UNICODE) : '{""}',
            'department_names' => ! empty($department_names) ? json_encode($department_names, JSON_UNESCAPED_UNICODE) : '{""}',
            'labels_title' => ! empty($labels_title) ? json_encode($labels_title, JSON_UNESCAPED_UNICODE) : '{""}',
            'cards' => true,
            'content' => $content,
            'upload_service' => Zeed_Config::loadGroup('urlmapping.upload_service')
        );

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.edit');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 添加 - 保存
     */
    public function addSave()
    {
        $set = $this->_validate();
        if ($set['status'] == 0) {
            try {
                $timenow = Util_Timer::getMicrotime();

                /* 组织基础信息，并入库 */
                $set_add_base = array(
                    'sn' => Support_Order::createSnForArchive(),
                    'title' => $set['data']['title'],
                    'category_name' => $set['data']['category_name'],
                    'department_name' => $set['data']['department_name'],
                    'respondent' => $set['data']['respondent'],
                    'description' => $set['data']['description'],
                    'label' => $set['data']['label'],
                    'tte' => $set['data']['tte'],
                    'region_id' => 0,
                    'region_name' => '',
                    'address' => '',
                    'userid' => $this->_userid,
                    'status' => 1,
                    'ctime' => $timenow,
                    'mtime' => $timenow
                );
                $content_id = Archive_Model_Content::instance()->addForEntity($set_add_base);

                /* 处理案件类型 - 将新的类型入库 */
                if ($set_add_base['category_name']) {
                    Trend_Helper_Category::add($set_add_base['category_name']);
                }

                /* 处理承办部门 - 将新的部门入库 */
                if ($set_add_base['department_name']) {
                    Trend_Helper_Department::add($set_add_base['department_name']);
                }

                /* 处理标签 - 将新的标签入库 */
                if ($set_add_base['label']) {
                    Trend_Helper_Label::add($set_add_base['label'], 1, $content_id);
                }

                /* 组织行动信息，并入库 */
                foreach ($set['data']['title_card'] as $k => $v) {
                    /* 处理时长详情 */
                    $duration_audio_detail = $duration_video_detail = '';
                    if ($set['data']['attachments_audio'][$k]) {
                        $attachments_audio_temp = explode(',', $set['data']['attachments_audio'][$k]);
                        $duration_audio_temp = explode(',', $set['data']['duration_audio'][$k]);
                        foreach ($attachments_audio_temp as $kk => $vv) {
                            $duration_audio_detail[$vv] = $duration_audio_temp[$kk] ? $duration_audio_temp[$kk] : 0;
                        }
                        $duration_audio_detail = json_encode($duration_audio_detail);
                    }
                    if ($set['data']['attachments_video'][$k]) {
                        $attachments_video_temp = explode(',', $set['data']['attachments_video'][$k]);
                        $duration_video_temp = explode(',', $set['data']['duration_video'][$k]);
                        foreach ($attachments_video_temp as $kk => $vv) {
                            $duration_video_detail[$vv] = $duration_video_temp[$kk] ? $duration_video_temp[$kk] : 0;
                        }
                        $duration_video_detail = json_encode($duration_video_detail);
                    }

                    /* 转化临时缓存的上传数据为正式数据 */
                    $attachments_img = Helper_Content::changeUploadTemp($set['data']['attachments_img'][$k]);
                    $attachments_audio = Helper_Content::changeUploadTemp($set['data']['attachments_audio'][$k]);
                    $attachments_video = Helper_Content::changeUploadTemp($set['data']['attachments_video'][$k]);

                    /* 入库 */
                    $set_add_card = array(
                        'sn' => $set_add_base['sn'],
                        'title' => $v,
                        'respondent' => $set['data']['respondent_card'][$k],
                        'description' => $set['data']['description_card'][$k],
                        'label' => $set['data']['label_card'][$k],
                        'attachments_img' => $attachments_img,
                        'attachments_audio' => $attachments_audio,
                        'attachments_video' => $attachments_video,
                        'duration_audio' => (int)$set['data']['duration_audio'][$k],
                        'duration_video' => (int)$set['data']['duration_video'][$k],
                        'duration_audio_detail' => $duration_audio_detail,
                        'duration_video_detail' => $duration_video_detail,
                        'tte_start' => $set['data']['tte_start_card'][$k],
                        'tte_end' => $set['data']['tte_end_card'][$k],
                        'region_id' => (int)$set['data']['region_id_card'][$k],
                        'region_name' => Trend_Helper_Region::getNameAllByRegionid($set['data']['region_id_card'][$k]),
                        'address' => $set['data']['address_card'][$k],
                        'userid' => $this->_userid,
                        'status' => 1,
                        'ctime' => $timenow
                    );
                    $card_id = Archive_Model_Card::instance()->addForEntity($set_add_card);

                    /* 处理标签 - 将新的标签入库 */
                    if ($set_add_card['label']) {
                        Trend_Helper_Label::add($set_add_card['label'], 2, $card_id);
                    }

                    /* 创建附件目录并绑定关系 */
                    $this->initFolder($set_add_base['sn'], $card_id, $attachments_img,
                        $attachments_audio, $attachments_video);
                }

                /* @todo 记录日志 */

                $data = array('content_id' => $content_id);
                $this->setData('data', $data);
            } catch (Zeed_Exception $e) {
                $this->setStatus(1);
                $this->setError('添加失败 : ' . $e->getMessage());
                return false;
            }
            return true;
        }
        $this->setStatus($set['status']);
        $this->setError($set['error']);
        return false;
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        if ($this->input->isPOST()) {
            $this->editSave();
            return self::RS_SUCCESS;
        }

        /* 接收参数 */
        $_id = $this->input->query('_id');
        $card_id = $this->input->query('card_id');

        /* 检查内容是否存在 */
        $content = Archive_Model_Content::instance()->fetchByPK($_id);
        if (empty($content)) {
            throw new Zeed_Exception('查无此案件。');
        }
        $content = $content[0];

        /* 处理标签 */
        $content['labels'] = explode(',', $content['label']);

        /* 获取相关行动 */
        $where_card = array('sn' => $content['sn'], 'status' => 1);
        $cards = Archive_Model_Card::instance()->fetchByWhere($where_card);

        /* 处理行动相关信息 */
        if (! empty($cards)) {
            foreach ($cards as $k => &$v) {
                /* 获取案件地点信息 */
                $region_info_card = Trend_Model_Region::instance()->fetchByPK($v['region_id']);
                $v['region_hid'] = $region_info_card[0]['hid'];
                $v['region_hid_arr'] = explode(':', $v['region_hid']);

                /* 处理标签 */
                $v['labels'] = explode(',', $v['label']);

                /* 处理附件 - 照片 */
                if ($v['attachments_img']) {
                    $attachments_img = explode(',', $v['attachments_img']);
                    $v['attachments_img_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_img);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_img_info'])) {
                        foreach ($v['attachments_img_info'] as $kk => $vv) {
                            /* 处理时间 */
                            $v['attachments_img_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理扩展信息 */
                            $v['attachments_img_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                            /* 处理容量 */
                            $v['attachments_img_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }

                /* 处理附件 - 录音 */
                if ($v['attachments_audio']) {
                    $attachments_audio = explode(',', $v['attachments_audio']);
                    $v['attachments_audio_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_audio);

                    /* 处理附件相关信息 */
                    foreach ($v['attachments_audio_info'] as $kk => $vv) {
                        /* 处理时间 */
                        $v['attachments_audio_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                        /* 处理扩展信息 */
                        $v['attachments_audio_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                        /* 处理容量 */
                        $v['attachments_audio_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                    }
                }

                /* 处理附件 - 录像 */
                if ($v['attachments_video']) {
                    $attachments_video = explode(',', $v['attachments_video']);
                    $v['attachments_video_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_video);

                    /* 处理附件相关信息 */
                    foreach ($v['attachments_video_info'] as $kk => $vv) {
                        /* 处理时间 */
                        $v['attachments_video_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                        /* 处理扩展信息 */
                        $v['attachments_video_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                        /* 处理容量 */
                        $v['attachments_video_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                    }
                }
            }
        }

        /* 获取案件类型 */
        $where_category = array('status' => 1);
        $order_category = "sort_order ASC";
        $categories = Archive_Model_Category::instance()->fetchByWhere($where_category, $order_category);
        $category_names = array();
        if (! empty($categories)) {
            foreach ($categories as $kk => $vv) {
                $category_names[] = $vv['title'];
            }
        }

        /* 获取承办部门 */
        $where_department = array('status' => 1);
        $order_department = "sort_order ASC";
        $departments = Archive_Model_Department::instance()->fetchByWhere($where_department, $order_department);
        $department_names = array();
        if (! empty($departments)) {
            foreach ($departments as $kk => $vv) {
                $department_names[] = $vv['department_name'];
            }
        }

        /* 获取热门标签 - 限制20条 */
        $order_label = array('rel_count' => 'DESC');
        $limit_label = 20;
        $labels = Trend_Model_Label::instance()->fetchByWhere(array(), $order_label, $limit_label);
        $labels_title = array();
        if (! empty($labels)) {
            foreach ($labels as $kk => $vv) {
                $labels_title[] = $vv['title'];
            }
        }

        /* 获取删除二次确认人信息 */
        $where_users_confirm = "u.status = 1 AND u.userid != 1 AND g.groupid = 1";
        $cols_users_confirm = array('u.userid', 'u.username', 'u.fullname');
        $users_confirm = Admin_Model_User::instance()->getUsersByGroupid($where_users_confirm, null, null, null, $cols_users_confirm);
        if (! empty($users_confirm)) {
            foreach ($users_confirm as $kk => $vv) {
                if ($vv['userid'] == $this->_userid) {
                    unset($users_confirm[$kk]);
                }
            }
        }

        $data = array(
                'content_id' => $_id,
                'card_id' => $card_id,
                'content' => $content,
                'cards' => $cards,
                'categories' => $categories,
                'departments' => $departments,
                'category_names' => ! empty($category_names) ? json_encode($category_names, JSON_UNESCAPED_UNICODE) : '{""}',
                'department_names' => ! empty($department_names) ? json_encode($department_names, JSON_UNESCAPED_UNICODE) : '{""}',
                'labels_title' => ! empty($labels_title) ? json_encode($labels_title, JSON_UNESCAPED_UNICODE) : '{""}',
                'users_confirm' => $users_confirm,
                'upload_service' => Zeed_Config::loadGroup('urlmapping.upload_service')
        );

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.edit');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 编辑 - 保存
     */
    public function editSave()
    {
        $set = $this->_validate();
        if ($set['status'] == 0) {
            try {
                $timenow = Util_Timer::getMicrotime();

                /* 查询案件是否已存在 */
                $content_info = Archive_Model_Content::instance()->fetchByPK($set['data']['content_id']);
                if (empty($content_info)) {
                    throw new Zeed_Exception('查无此案件');
                }
                $content_info = $content_info[0];

                /* 更新基本信息 */
                $set_update_base = array(
                    'title' => $set['data']['title'],
                    'category_name' => $set['data']['category_name'],
                    'department_name' => $set['data']['department_name'],
                    'respondent' => $set['data']['respondent'],
                    'description' => $set['data']['description'],
                    'label' => $set['data']['label'],
                    'tte' => $set['data']['tte'],
                    'mtime' => $timenow
                );
                Archive_Model_Content::instance()->updateForEntity($set_update_base, $content_info['_id']);

                /* 处理案件类型 - 将新的类型入库 */
                if ($set_update_base['category_name']) {
                    Trend_Helper_Category::add($set_update_base['category_name']);
                }

                /* 处理承办部门 - 将新的部门入库 */
                if ($set_update_base['department_name']) {
                    Trend_Helper_Department::add($set_update_base['department_name']);
                }

                /* 处理标签 - 将新的标签入库 */
                if ($set_update_base['label']) {
                    Trend_Helper_Label::add($set_update_base['label'], 1, $set['data']['content_id']);
                }

                /* 处理行动信息 - 更新 / 新增 */
                foreach ($set['data']['card_id'] as $k => $v) {
                    /* 处理时长详情 */
                    $duration_audio_detail = $duration_video_detail = '';
                    if ($set['data']['attachments_audio'][$k]) {
                        $attachments_audio_temp = explode(',', $set['data']['attachments_audio'][$k]);
                        $duration_audio_temp = explode(',', $set['data']['duration_audio'][$k]);
                        foreach ($attachments_audio_temp as $kk => $vv) {
                            $duration_audio_detail[$vv] = $duration_audio_temp[$kk] ? $duration_audio_temp[$kk] : 0;
                        }
                        $duration_audio_detail = json_encode($duration_audio_detail);
                    }
                    if ($set['data']['attachments_video'][$k]) {
                        $attachments_video_temp = explode(',', $set['data']['attachments_video'][$k]);
                        $duration_video_temp = explode(',', $set['data']['duration_video'][$k]);
                        foreach ($attachments_video_temp as $kk => $vv) {
                            $duration_video_detail[$vv] = $duration_video_temp[$kk] ? $duration_video_temp[$kk] : 0;
                        }
                        $duration_video_detail = json_encode($duration_video_detail);
                    }

                    /* 转化临时缓存的上传数据为正式数据 */
                    $attachments_img = Helper_Content::changeUploadTemp($set['data']['attachments_img'][$k], true);
                    $attachments_audio = Helper_Content::changeUploadTemp($set['data']['attachments_audio'][$k], true);
                    $attachments_video = Helper_Content::changeUploadTemp($set['data']['attachments_video'][$k], true);

                    if ($v) {
                        /* 获取行动信息 */
                        $card_info = Archive_Model_Card::instance()->fetchByPK($v);

                        /* 更新 */
                        $set_update_card = array(
                            'title' => $set['data']['title_card'][$k],
                            'respondent' => $set['data']['respondent_card'][$k],
                            'description' => $set['data']['description_card'][$k],
                            'label' => $set['data']['label_card'][$k],
                            'attachments_img' => $attachments_img,
                            'attachments_audio' => $attachments_audio,
                            'attachments_video' => $attachments_video,
                            'duration_audio' => (int)$set['data']['duration_audio'][$k],
                            'duration_video' => (int)$set['data']['duration_video'][$k],
                            'duration_audio_detail' => $duration_audio_detail,
                            'duration_video_detail' => $duration_video_detail,
                            'tte_start' => $set['data']['tte_start_card'][$k],
                            'tte_end' => $set['data']['tte_end_card'][$k],
                            'region_id' => (int)$set['data']['region_id_card'][$k],
                            'region_name' => Trend_Helper_Region::getNameAllByRegionid($set['data']['region_id_card'][$k]),
                            'address' => $set['data']['address_card'][$k],
                        );
                        Archive_Model_Card::instance()->updateForEntity($set_update_card, $v);

                        /* 附件处理 - 照片 */
                        $this->_updateArchiveAttachment('image', $card_info[0]['attachments_img'],
                            $attachments_img, $v, $card_info[0]);

                        /* 附件处理 - 录音 */
                        $this->_updateArchiveAttachment('audio', $card_info[0]['attachments_audio'],
                            $attachments_audio, $v, $card_info[0]);

                        /* 附件处理 - 录像 */
                        $this->_updateArchiveAttachment('video', $card_info[0]['attachments_video'],
                            $attachments_video, $v, $card_info[0]);
                    } else {
                        /* 新增 */
                        $set_add_card = array(
                            'sn' => $content_info['sn'],
                            'title' => $set['data']['title_card'][$k],
                            'respondent' => $set['data']['respondent_card'][$k],
                            'description' => $set['data']['description_card'][$k],
                            'label' => $set['data']['label_card'][$k],
                            'attachments_img' => $attachments_img,
                            'attachments_audio' => $attachments_audio,
                            'attachments_video' => $attachments_video,
                            'duration_audio' => (int)$set['data']['duration_audio'][$k],
                            'duration_video' => (int)$set['data']['duration_video'][$k],
                            'duration_audio_detail' => $duration_audio_detail,
                            'duration_video_detail' => $duration_video_detail,
                            'tte_start' => $set['data']['tte_start_card'][$k],
                            'tte_end' => $set['data']['tte_end_card'][$k],
                            'region_id' => (int)$set['data']['region_id_card'][$k],
                            'region_name' => Trend_Helper_Region::getNameAllByRegionid($set['data']['region_id_card'][$k]),
                            'address' => $set['data']['address_card'][$k],
                            'status' => 1,
                            'ctime' => $timenow
                        );
                        $v = Archive_Model_Card::instance()->addForEntity($set_add_card);

                        /* 创建附件目录并绑定关系 */
                        $this->initFolder($content_info['sn'], $v, $attachments_img,
                            $attachments_audio, $attachments_video);
                    }

                    /* 处理标签 - 将新的标签入库 */
                    if ($set['data']['label_card'][$k]) {
                        Trend_Helper_Label::add($set['data']['label_card'][$k], 2, $v);
                    }
                }

                /* 处理要申请删除的行动 */
                if (! empty($set['data']['delete_card_id'])) {
                    $this->deleteCard($set['data']['delete_card_id']);
                }

                /* 处理要申请删除的资料 */
                if (! empty($set['data']['delete_a_id'])) {
                    Helper_Attachment::delete($set['data']['delete_a_id'], $this->_userid);
                }

                /* 更新分享出去的案件信息 */
                $where_share = array('sn' => $content_info['sn']);
                $set_share = array(
                    'title' => $set['data']['title'],
                    'category_name' => $set['data']['category_name'],
                    'department_name' => $set['data']['department_name'],
                    'description' => $set['data']['description'],
                    'label' => $set['data']['label'],
                    'tte' => $set['data']['tte'],
                    'mtime' => $timenow
                );
                Archive_Model_Share::instance()->update($set_share, $where_share);

                /* @todo 记录日志 */
                /*$set_log = array(
                        'action_type' => 'update',
                        'userid' => $this->_userid,
                        'content_before' => json_encode($content_info),
                        'content_after' => json_encode($content_after),
                        'ip' => Zeed_Util::clientIP(),
                        'ua' => $_SERVER['HTTP_USER_AGENT'],
                        'ctime' => $timenow
                );
                Shortvideo_Model_Program_Content_Log::instance()->addForEntity($set_log, 'Shortvideo');*/
            } catch (Zeed_Exception $e) {
                $this->setStatus(1);
                $this->setError('编辑失败 : ' . $e->getMessage());
                return false;
            }
            return true;
        }
        $this->setStatus($set['status']);
        $this->setError($set['error']);
        return false;
    }

    /**
     * 保存 － 校验
     */
    private function _validate()
    {
        $res = array('status' => 0, 'error' => null, 'data' => null);

        try {
            $res['data'] = $this->input->post();

            /* 数据验证 - 基础信息 */
            if (!$res['data']['title'] || !$res['data']['tte'] || !$res['data']['category_name'] ||
                !$res['data']['department_name']
            ) {
                throw new Zeed_Exception('请填写完所有必填项');
            }

            /* 数据验证 - 行动信息 */
            if (!is_array($res['data']['title_card'])) {
                throw new Zeed_Exception('请至少填写一个行动');
            }
            foreach ($res['data']['title_card'] as $k => $v) {
                if (!$v || !$res['data']['tte_start_card'][$k] || !$res['data']['tte_end_card'][$k] || !$res['data']['respondent_card'][$k] ||
                    !$res['data']['region_id_card'][$k] || $res['data']['region_id_card'][$k] == 0 || !$res['data']['address_card'][$k]
                ) {
                    throw new Zeed_Exception('请至少填写一个完整的行动');
                }
                if ($res['data']['tte_start_card'][$k] > $res['data']['tte_end_card'][$k]) {
                    throw new Zeed_Exception('请确保行动中的结束时间大于开始时间');
                }
            }
        } catch (Zeed_Exception $e) {
            $res['status'] = 1;
            $res['error'] = $e->getMessage();
        }

        return $res;
    }

    /**
     * 详情
     */
    public function detail()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $_id = $this->input->get('_id');
        $card_id = $this->input->query('card_id');

        /* 查询案件详情 */
        $content = Archive_Model_Content::instance()->fetchByPK($_id);
        if (empty($content) || ($content[0]['status'] != 1 && $content[0]['status'] != -2)) {
            throw new Zeed_Exception('查无此案件');
        }
        $content = $content[0];

        /* 获取相关行动 */
        $where_card = array('sn' => $content['sn'], 'status' => 1);
        $cards = Archive_Model_Card::instance()->fetchByWhere($where_card);

        /* 处理行动相关信息 */
        if (! empty($cards)) {
            foreach ($cards as $k => &$v) {
                /* 获取案件地点信息 */
                $region_info_card = Trend_Model_Region::instance()->fetchByPK($v['region_id']);
                $v['region_hid'] = $region_info_card[0]['hid'];
                $v['region_hid_arr'] = explode(':', $v['region_hid']);

                /* 获取父级目录信息以及子目录信息 */
                $folders = $this->_getFirstFolders($v);
                $v['parent_folder'] = $folders['parent_folder'];
                $v['child_folders'] = $folders['child_folders'];
                $v['child_folders_forselect'] = $folders['child_folders_forselect'];

                /* 处理附件 - 照片 */
                if ($v['attachments_img']) {
                    $attachments_img = explode(',', $v['attachments_img']);
                    $v['attachments_image_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_img);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_image_info'])) {
                        foreach ($v['attachments_image_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_image_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_image_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理容量 */
                            $v['attachments_image_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }

                /* 处理附件 - 录音 */
                if ($v['attachments_audio']) {
                    $attachments_audio = explode(',', $v['attachments_audio']);
                    $v['attachments_audio_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_audio);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_audio_info'])) {
                        foreach ($v['attachments_audio_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_audio_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_audio_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理扩展信息 */
                            $v['attachments_audio_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                            /* 处理容量 */
                            $v['attachments_audio_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }

                /* 处理附件 - 录像 */
                if ($v['attachments_video']) {
                    $attachments_video = explode(',', $v['attachments_video']);
                    $v['attachments_video_info'] = Attachment_Model_Content::instance()->fetchByPK($attachments_video);

                    /* 处理附件相关信息 */
                    if (! empty($v['attachments_video_info'])) {
                        foreach ($v['attachments_video_info'] as $kk => $vv) {
                            /* 过滤 */
                            if ($vv['status'] != 1) {
                                unset($v['attachments_video_info'][$kk]);
                                continue;
                            }

                            /* 处理时间 */
                            $v['attachments_video_info'][$kk]['ctime'] = Util_Timer::formatMicrotime($vv['ctime'], 'Y-m-d H:i:s');

                            /* 处理扩展信息 */
                            $v['attachments_video_info'][$kk]['extra'] = $vv['extra'] ? json_decode($vv['extra'], true) : array();

                            /* 处理容量 */
                            $v['attachments_video_info'][$kk]['filesize_format'] = Util_File::formatFilesize($vv['filesize']);
                        }
                    }
                }
            }
        }

        $data = array(
            'content' => $content,
            'card_id' => $card_id,
            'cards' => $cards
        );

        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.detail');
        return parent::multipleResult(self::RS_SUCCESS);
    }

    /**
     * 申请删除案件
     */
    public function deleteArchive()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $userid = (int)$this->input->query('userid');
        $sn = $this->input->query('sn');

        try {
            /* 检查请求方式 */
            if (!$this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }

            /* 检查请求参数 */
            if (!$userid || !$sn) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }

            /* 检查案件是否存在 */
            $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $sn);
            if (empty($archive_info)) {
                throw new Zeed_Exception('查无此案件');
            }
            $archive_info = $archive_info[0];

            /* 组织数据并入库 */
            $timenow = Util_Timer::getMicrotime();
            $set_add = array(
                'type' => 1,
                'sn' => $sn,
                'userid_proposer' => $this->_userid,
                'userid_verifier' => $userid,
                'memo' => '',
                'status' => 0,
                'ctime' => $timenow,
                'mtime' => $timenow
            );
            $confirm_id = Archive_Model_Confirm::instance()->addForEntity($set_add);

            /* 更新案件状态 */
            $set_update = array(
                'status' => -2,
                'mtime' => $timenow
            );
            Archive_Model_Content::instance()->updateForEntity($set_update, $archive_info['_id']);

            /* 新增一条通知消息记录 */
            Zeed_Hook::exec('Hooks.Notify.ArchiveDeleteConfirm',
                array(
                    'send_userid' => $this->_userid,
                    'to_userid' => $userid,
                    'sn' => $sn,
                    'confirm_id' => $confirm_id
                ));

            /* 删除分享出去案件信息 */
            Archive_Model_Share::instance()->deleteByFV('sn', $sn);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('提交失败 : ' . $e->getMessage());
        }

        return self::RS_SUCCESS;
    }

    /**
     * 申请删除行动
     *
     * @param string $cards 要删除的行动
     *      格式：【_id:userid】
     *      多个以半角逗号分隔
     */
    public function deleteCard($cards)
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        try {
            /* 处理参数 */
            $cards_arr = explode(',', $cards);
            $timenow = Util_Timer::getMicrotime();

            if (! empty($cards_arr)) {
                foreach ($cards_arr as $k => $v) {
                    $card_detail = explode(':', $v);

                    /* 组织数据并入库 */
                    $set_add = array(
                        'type' => 2,
                        'sn' => $card_detail[0],
                        'userid_proposer' => $this->_userid,
                        'userid_verifier' => (int)$card_detail[1],
                        'memo' => '',
                        'status' => 0,
                        'ctime' => $timenow,
                        'mtime' => $timenow
                    );
                    $confirm_id = Archive_Model_Confirm::instance()->addForEntity($set_add);

                    /* 更新行动状态 */
                    $set_update = array(
                        'status' => -2
                    );
                    Archive_Model_Card::instance()->updateForEntity($set_update, $card_detail[0]);

                    /* 新增一条通知消息记录 */
                    Zeed_Hook::exec('Hooks.Notify.CardDeleteConfirm',
                        array(
                            'send_userid' => $this->_userid,
                            'to_userid' => $card_detail[1],
                            'sn' => $card_detail[0],
                            'confirm_id' => $confirm_id
                        ));
                }
            }
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('提交失败 : ' . $e->getMessage());
        }

        return self::RS_SUCCESS;
    }

    /**
     * 处理案件和行动删除的申请
     */
    public function operateDelete()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        /* 接收参数 */
        $confirm_id = $this->input->query('confirm_id');
        $status = (int)$this->input->query('status');
        $memo = $this->input->query('memo');

        try {
            /* 检查请求方式 */
            if (!$this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }

            /* 检查请求参数 */
            if (!$confirm_id || !$status) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }

            /* 检查申请内容是否存在 */
            $confirm_info = Archive_Model_Confirm::instance()->fetchByPK($confirm_id);
            if (empty($confirm_info)) {
                throw new Zeed_Exception('申请内容不存在');
            }
            $confirm_info = $confirm_info[0];

            /* 组织数据并入库 */
            $timenow = Util_Timer::getMicrotime();
            $set_update = array(
                'status' => $status,
                'memo' => $memo,
                'mtime' => $timenow
            );
            Archive_Model_Confirm::instance()->updateForEntity($set_update, $confirm_id);

            /* 处理案件、行动或资料的删除 */
            if ($status == 1) {
                /* 同意删除 */
                if ($confirm_info['type'] == 1) {
                    /* 删除案件 */
                    $set_update_archive = array(
                        'status' => -1,
                        'mtime' => $timenow
                    );
                    $where_archive = array('sn' => $confirm_info['sn']);
                    Archive_Model_Content::instance()->update($set_update_archive, $where_archive);

                    /* 查出其下所有行动 */
                    $cards = Archive_Model_Card::instance()->fetchByFV('sn', $confirm_info['sn']);

                    /* 删除其下行动 */
                    $set_update_card = array(
                        'status' => -1,
                    );
                    $where_card = array('sn' => $confirm_info['sn']);
                    Archive_Model_Card::instance()->update($set_update_card, $where_card);

                    /* 删除其下资料、及生产出来的文件 */
                    if (! empty($cards)) {
                        $set_update_attachment = array(
                            'status' => -2,
                            'mtime' => $timenow
                        );
                        $attachment_ids = array();
                        foreach ($cards as $k => $v) {
                            $attachment_ids = array_merge($attachment_ids, explode(',', $v['attachments_img']),
                                explode(',', $v['attachments_audio']), explode(',', $v['attachments_video']));
                        }
                        $attachment_ids = array_values(array_unique(array_filter($attachment_ids))); // 去空值、去重、重建索引
                        if (! empty($attachment_ids)) {
                            foreach ($attachment_ids as $k => $v) {
                                Attachment_Model_Content::instance()->updateForEntity($set_update_attachment, $v);
                                $where_children = array('pid' => $v);
                                Attachment_Model_Content::instance()->update($set_update_attachment, $where_children);
                            }
                        }
                    }

                    /* 删除其下的打点信息 */
                    $set_dot = array('status' => -1, 'mtime' => $timenow);
                    $where_dot = array('sn' => $confirm_info['sn']);
                    Attachment_Model_Content_Dot::instance()->update($set_dot, $where_dot);
                } elseif ($confirm_info['type'] == 2) {
                    /* 查询行动信息 */
                    $card = Archive_Model_Card::instance()->fetchByPK($confirm_info['sn']);

                    /* 删除行动 */
                    $set_update_card = array(
                        'status' => -1,
                    );
                    Archive_Model_Card::instance()->updateForEntity($set_update_card, $confirm_info['sn']);

                    /* 删除其下资料、及生产出来的文件 */
                    if (! empty($card)) {
                        $set_update_attachment = array(
                            'status' => -2,
                            'mtime' => $timenow
                        );
                        $attachment_ids = array();
                        $attachment_ids = array_merge($attachment_ids, explode(',', $card[0]['attachments_img']),
                            explode(',', $card[0]['attachments_audio']), explode(',', $card[0]['attachments_video']));
                        $attachment_ids = array_values(array_unique(array_filter($attachment_ids))); // 去空值、去重、重建索引
                        if (! empty($attachment_ids)) {
                            foreach ($attachment_ids as $k => $v) {
                                Attachment_Model_Content::instance()->updateForEntity($set_update_attachment, $v);
                                $where_children = array('pid' => $v);
                                Attachment_Model_Content::instance()->update($set_update_attachment, $where_children);
                            }
                        }
                    }

                    /* 删除其下的打点信息 */
                    $set_dot = array('status' => -1, 'mtime' => $timenow);
                    $where_dot = array('card_id' => $confirm_info['sn']);
                    Attachment_Model_Content_Dot::instance()->update($set_dot, $where_dot);
                } elseif ($confirm_info['type'] == 3) {
                    /* 删除资料 */
                    $set_update_attachment = array(
                        'status' => -2,
                        'mtime' => $timenow
                    );
                    Attachment_Model_Content::instance()->updateForEntity($set_update_attachment, $confirm_info['sn']);

                    /* 删除其下生产出来的文件 */
                    $where_children = array('pid' => $confirm_info['sn']);
                    Attachment_Model_Content::instance()->update($set_update_attachment, $where_children);

                    /* 删除其下的打点信息 */
                    $set_dot = array('status' => -1, 'mtime' => $timenow);
                    $where_dot = array('attachment_id' => $confirm_info['sn']);
                    Attachment_Model_Content_Dot::instance()->update($set_dot, $where_dot);
                }
            } elseif ($status == 2) {
                /* 拒绝删除 */
                if ($confirm_info['type'] == 1) {
                    /* 还原案件状态 */
                    $set_update_archive = array(
                        'status' => 1,
                        'mtime' => $timenow
                    );
                    $where_archive = array('sn' => $confirm_info['sn']);
                    Archive_Model_Content::instance()->update($set_update_archive, $where_archive);
                } elseif ($confirm_info['type'] == 2) {
                    /* 还原行动状态 */
                    $set_update_card = array(
                        'status' => 1,
                    );
                    Archive_Model_Card::instance()->updateForEntity($set_update_card, $confirm_info['sn']);
                } elseif ($confirm_info['type'] == 3) {
                    /* 还原资料状态 */
                    $set_update_attachment = array(
                        'status' => 1,
                    );
                    Attachment_Model_Content::instance()->updateForEntity($set_update_attachment, $confirm_info['sn']);
                }
            }

            /* @todo 新增一条回馈通知消息记录（待后期优化时处理） */
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('处理失败 : ' . $e->getMessage());
        }

        return self::RS_SUCCESS;
    }

    /**
     * 上传附件
     */
    public function uploadFile()
    {
        $this->addResult(self::RS_SUCCESS, 'json');

        if ($_FILES['files']['error'] == UPLOAD_ERR_OK) {
            try {
                $upload_arr = $_FILES['files'];

                /* 获取登录用户信息 */
                $user_info = Com_Admin_Authorization::getLoggedInUser();

                /* 文件类型判断 */
                $allow_type = array('');
//                 $mimeType = Zeed_File_MIMEType::mime($upload_arr['tmp_name']);
//                 $mimeType = strstr($mimeType, ';') ? substr($mimeType, 0, strrpos($mimeType, ';')) : $mimeType;
//                 $temp_mimetype = explode('/', $mimeType);
//                 if (strtolower($temp_mimetype[0]) != 'image') {
//                     throw new Zeed_Exception('仅支持照片上传');
//                 }

                /* 上传参数处理 */
                $srcFile = $upload_arr['tmp_name'];
                $pos = strrpos($upload_arr['name'], '.');
                $suffix = $pos ? substr($upload_arr['name'], $pos + 1) : null;
                $title = $pos ? substr($upload_arr['name'], 0, $pos) : $upload_arr['name'];

                /* 执行上传 - 数据存入附件缓存表 */
                $attach = Trend_Attachment_Temp::add($srcFile, $suffix, $user_info['userid'], $title);
                $attach['thumbsrc'] = $this->_generateThumbnailsUrl($attach['filepath'], $attach['mimetype'], 'AM');
                if (is_array($attach) && isset($attach['_id']) && $attach['_id'] > 0) {
                    /* 处理时间 */
                    $attach['ctime'] = Util_Timer::formatMicrotime($attach['ctime'], 'Y-m-d H:i:s');

                    /* 处理扩展信息 */
                    $attach['extra'] = $attach['extra'] ? json_decode($attach['extra'], true) : array();

                    /* 处理时长 */
                    if (isset($attach['extra']['duration'])) {

                    }

                    /* 处理封面 */
                    if (isset($attach['extra']['cover'])) {
                        $config_storage = Zeed_Storage::instance()->getConfig();
                        $attach['extra']['cover'] = $config_storage['url_prefix_b'] . $attach['extra']['cover'];
                    }

                    /* 处理容量 */
                    $attach['filesize_format'] = Util_File::formatFilesize($attach['filesize']);

                    $data = $attach;
                } else {
                    throw new Zeed_Exception('上传文件失败');
                }
            } catch (Zeed_Exception $e) {
                $this->setStatus(1);
                $this->setError($e->getMessage());
                return self::RS_SUCCESS;
            }
        } else {
            $this->setStatus(1);
            $this->setError('文件大小超出服务器限制');
            return self::RS_SUCCESS;
        }

        $this->setData('data', $data);
        return self::RS_SUCCESS;
    }

    /**
     * 产生缩略图(JPEG格式)地址或文件类型图标地址 注意: 缩略图的扩展名可能不代表其真实的MIMEType
     *
     * @param boolean $filepath
     * @param string $mimetype 文件的MIMEType类型
     * @param string $thumbScheme 指定的已配置缩略图方案
     * @param string $urlPrefix 上传目录可访问地址
     * @return string 返回缩略图地址
     */
    protected function _generateThumbnailsUrl($filepath, $mimetype, $thumbScheme, $urlPrefix = null)
    {
        if (substr($mimetype, 0, 6) != 'image/') {
            $configIconsAttachment = Zeed_Config::loadGroup('icon.attachment');
            if (!isset($configIconsAttachment['list'][$mimetype])) {
                $thumbUrl = $configIconsAttachment['default'];
            } else {
                $thumbUrl = $configIconsAttachment['list'][$mimetype];
            }
            return $thumbUrl;
        }

        $thumbUrl = '';
        $suffix = substr($filepath, strrpos($filepath, '.'));
        $thumbUrl = str_replace($suffix, '_' . $thumbScheme . $suffix, $filepath);

        if (is_null($urlPrefix)) {
            $config = Zeed_Storage::instance()->getConfig();
            $thumbUrl = $config['url_thumb_mng_prefix'] . $thumbUrl;
        } else {
            $thumbUrl = $urlPrefix . $thumbUrl;
        }

        return $thumbUrl;
    }

    /**
     * 更新案件附件关系
     *
     * @param string $type 附件类型：照片、录音、录像
     * @param string $aids_old 旧的附件 ID 集合，逗号拼接
     * @param string $aids_new 新提交的附件 ID 集合，逗号拼接
     * @param string $card_id 资料卡 ID
     * @param array $card_info 行动信息
     * @return boolean
     */
    protected function _updateArchiveAttachment($type, $aids_old, $aids_new, $card_id, $card_info)
    {
        $timenow = Util_Timer::getMicrotime();

        /* 附件 ID 处理 */
        $aids_old = $aids_old ? explode(',', $aids_old) : array();
        $aids_new = $aids_new ? explode(',', $aids_new) : array();

        /* 新增附件 - 绑定与文件夹的关系 */
        if (! empty($aids_new)) {
            $where_folder = array(
                'parent_id' => 0,
                'card_id' => $card_id,
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_' . $type . '_' . $card_id
            );
            $folder_info = Attachment_Model_Folder::instance()->fetchByWhere($where_folder);
            foreach ($aids_new as $ka => $va) {
                if (! in_array($va, $aids_old)) {
                    $set_update = array(
                        'folder_hid' => $folder_info[0]['hid'],
                        'mtime' => $timenow
                    );
                    Attachment_Model_Content::instance()->updateForEntity($set_update, $va);
                }
            }
        }

        /* 删除附件 */
        /* @todo 这里的附件不能删除，需要走二次确认策略 */
//         if (! empty($aids_old)) {
//             foreach ($aids_old as $ka => $va) {
//                 if (! in_array($va, $aids_new)) {
//                     Attachment_Model_Content::instance()->deleteByPK($va);
//                 }
//             }
//         }

        return true;
    }

    /**
     * 获取根目录下的子目录信息
     *
     * @param array $card_info 资料卡信息
     * @return boolean
     */
    protected function _getFirstFolders($card_info)
    {
        /* 处理照片类型 */
        $where_folder_image = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_image_' . $card_info['_id']
        );
        $folder_info_image = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_image);

        $where_child_folders_image = array(
                'parent_id' => $folder_info_image[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['image'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_image);

        /* 处理录音类型 */
        $where_folder_audio = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_audio_' . $card_info['_id']
        );
        $folder_info_audio = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_audio);

        $where_child_folders_audio = array(
                'parent_id' => $folder_info_audio[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['audio'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_audio);

        /* 处理录像类型 */
        $where_folder_video = array(
                'parent_id' => 0,
                'card_id' => $card_info['_id'],
                'title' => date('Y-m-d', intval($card_info['ctime'] / 1000)) . '_video_' . $card_info['_id']
        );
        $folder_info_video = Attachment_Model_Folder::instance()->fetchByWhere($where_folder_video);

        $where_child_folders_video = array(
                'parent_id' => $folder_info_video[0]['fid'],
                'card_id' => $card_info['_id'],
                'status' => 1
        );
        $child_folders['video'] = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folders_video);

        /* 汇总返回信息 */
        $folders = array(
                'parent_folder' => array(
                        'image' => $folder_info_image[0],
                        'audio' => $folder_info_audio[0],
                        'video' => $folder_info_video[0]
                ),
                'child_folders' => $child_folders
        );
        return $folders;
    }
}

// End ^ LF ^ encoding
